package cn.sixmillions.mb.config;

import cn.sixmillions.mb.io.Resources;
import cn.sixmillions.mb.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 解析SqlMapConfig.xml配置文件为Configuration对象
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        //创建configuration成员变量
        this.configuration = new Configuration();
    }

    /**
     * 读取配置文件
     *
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        //dom4j解析配置文件输入流
        Document document = new SAXReader().read(inputStream);
        //根对象，也就是<configuration>
        Element rootElement = document.getRootElement();
        List<Element> propertyElementList = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        //解析
        for (Element propertyElement : propertyElementList) {
            String name = propertyElement.attributeValue("name");
            String value = propertyElement.attributeValue("value");
            properties.setProperty(name, value);
        }
        //数据连接池对象，这里使用c3p0里面的
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        //将数据库连接池对象放到configuretion
        configuration.setDataSource(comboPooledDataSource);

        //mapper.xml解析
        //1. 拿到mapper文件路径，读取输入流，dom4j解析
        List<Element> mapperElementList = rootElement.selectNodes("//mapper");
        for (Element mapperElement : mapperElementList) {
            String mapperPath = mapperElement.attributeValue("resource");
            //mapper.xml输入流
            InputStream mapperStream = Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(mapperStream);
        }
        return configuration;
    }
}
